package cn.bitkit.tools.file;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import net.coobird.thumbnailator.Thumbnails;

@Slf4j
public class ImageUtil {
	
	public static final int SIZE_10M = 10*1024*1024;
	public static final int SIZE_5M = 5*1024*1024;
	public static final int SIZE_1M = 1024 * 1024;

	public static InputStream compress(InputStream is) {
		return compress(is, SIZE_1M);
	}

	@SneakyThrows
	public static InputStream compress(InputStream is, int size) {
		if(is.available() < size) {
			return is;
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		double scale = ((double)size)/is.available();
		Thumbnails.of(is).scale(scale).outputQuality(1).toOutputStream(os);
		return new ByteArrayInputStream(os.toByteArray());
	}
}
